package com.rc.saas.mini.client;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rc.saas.mini.common.base.TResponse;
import com.rc.saas.mini.common.constant.HttpConstant;
import com.rc.saas.mini.common.constant.RouterConfig;
import com.rc.saas.mini.mapper.member.MemberInfoMapper;
import com.rc.saas.mini.mapper.order.OrderInfoMapper;
import com.rc.saas.mini.model.elec.ElecPileHost;
import com.rc.saas.mini.model.member.MemberInfo;
import com.rc.saas.mini.model.order.OrderInfo;
import com.rc.saas.mini.service.elec.ElecPileHostService;
import com.rc.saas.mini.utils.RestTemplateUtil;
import com.rc.saas.mini.vo.cec.StdRequest;
import com.rc.saas.mini.vo.charge.CommandStartReq;
import com.rc.saas.mini.vo.charge.CommandStopReq;
import com.rc.saas.mini.vo.elec.UserAccountVo;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

/**
 * 多品牌充电服务器域名,STD_DOMAIN,ZC_DOMAIN
 * Created by sven on 2019/12/13
 */
@Component
public class ChargerClientRouter {
    private static Logger logger = LogManager.getLogger(ChargerClientRouter.class);

    @Autowired
    private StdEvchargerClient1 stdEvchargerClient1;

    @Autowired
    private StdEvchargerClient2 stdEvchargerClient2;

    @Autowired
    private MutiEvchargerClient1 mutiEvchargerClient1;

    @Autowired
    private MemberInfoMapper memberInfoMapper;

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private ElecPileHostService elecPileHostService;

    @Autowired
    private RestTemplateUtil restTemplateUtil;


    /**
     *下达开始充电指令
     @param elecServerDomain  部署服务器
     @param elecServerSpliter 分流服务器
     @param tRequest
     @return
     */
    public TResponse query_start_charge(String elecServerDomain, int elecServerSpliter, StdRequest tRequest, CommandStartReq commandStartReq) {
        //查地址表
        ElecPileHost elecPileHost = elecPileHostService.selectByPrimaryKey(commandStartReq.getElecPileId());

        //拼接eureka访问地址
        String requestUrl = RouterConfig.WECHAT_START_CHARGE_PATH;
        if (HttpConstant.STD_DOMAIN.equals(elecPileHost.getElecServerDomain())) {
            requestUrl = "http://" + elecPileHost.getApplicationName() + RouterConfig.STD_SERVICE_PATH + RouterConfig.APP_START_CHARGE_PATH;
        } else {
            requestUrl = "http://" + elecPileHost.getApplicationName() + RouterConfig.MUL_SERVICE_PATH + RouterConfig.MUTI_WECHAT_START_CHARGE_PATH;
        }

        ObjectMapper objectMapper = new ObjectMapper();
        String respData = null;
        try {
            respData = objectMapper.writeValueAsString(tRequest);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        JSONObject tRequestJson = JSONObject.parseObject(respData);

        logger.info("std入参加密接口,启动充电路由被调用，...............对应url:{},orderSource:{}", requestUrl);
        //通过rest调用远程服务接口
        ResponseEntity<TResponse> request = restTemplateUtil.request(requestUrl, HttpMethod.POST, tRequestJson, TResponse.class);
        logger.info("std入参加密接口,启动充电路由被调用，...............返回状态码:{},结果集:{}", request.getStatusCode(), request.getBody().toString());
        return request.getBody();
    }

    /**
     * 下达结束充电指令
     *
     * @param elecServerDomain  部署服务器
     * @param elecServerSpliter 分流服务器
     * @param tRequest
     * @return
     */
    public TResponse query_stop_charge(String elecServerDomain, int elecServerSpliter, StdRequest tRequest, CommandStopReq commandStopReq) {
        //查地址表
        ElecPileHost elecPileHost = elecPileHostService.selectByPrimaryKey(commandStopReq.getElecPileId());

        //拼接eureka访问地址
        String requestUrl = RouterConfig.WECHAT_STOP_CHARGE_PATH;
        if (HttpConstant.STD_DOMAIN.equals(elecPileHost.getElecServerDomain())) {
            requestUrl = "http://" + elecPileHost.getApplicationName() + RouterConfig.STD_SERVICE_PATH + RouterConfig.APP_STOP_CHARGE_PATH;
        } else {
            requestUrl = "http://" + elecPileHost.getApplicationName() + RouterConfig.MUL_SERVICE_PATH + RouterConfig.MUTI_WECHAT_STOP_CHARGE_PATH;
        }

        ObjectMapper objectMapper = new ObjectMapper();
        String respData = null;
        try {
            respData = objectMapper.writeValueAsString(tRequest);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        JSONObject tRequestJson = JSONObject.parseObject(respData);

        logger.info("std入参加密接口,停止充电路由被调用，...............对应url:{},orderSource:{}", requestUrl);
        //通过rest调用远程服务接口
        ResponseEntity<TResponse> request = restTemplateUtil.request(requestUrl, HttpMethod.POST, tRequestJson, TResponse.class);
        logger.info("std入参加密接口,停止充电路由被调用，...............返回状态码:{},结果集:{}", request.getStatusCode(), request.getBody().toString());
        return request.getBody();
    }

    /**
     * 后台结算订单
     */
    public TResponse updateOrder(String elecServerDomain, int elecServerSpliter, Long orderId) {
        //桩群表的充电服务器域名DOMAIN1,DOMAIN2
        if (elecServerDomain.equals(HttpConstant.STD_DOMAIN)) {//标准桩
            switch (elecServerSpliter) {
                case 0:
                    return stdEvchargerClient1.updateOrder(orderId);//37
                case 1:
                    return stdEvchargerClient2.updateOrder(orderId);//221
            }
        } else {//非标桩
            return stdEvchargerClient2.updateOrder(orderId);//221
        }

        return null;
    }

    /**
     * 余额下发功能
     */
    public TResponse sendUserAccount(Long memberId, String memberType) {

        MemberInfo memberInfo = memberInfoMapper.selectByPrimaryKey(memberId);
        // 互联互通账号不参与
        if ("3".equals(memberInfo.getMemberType())) {
            return TResponse.FAIL();
        }
        OrderInfo orderInfo = orderInfoMapper.selectNewOrderByMemberId(memberId);
        if (orderInfo == null || "2".equals(orderInfo.getStatus())) {
            return TResponse.FAIL();
        }

        UserAccountVo userAccountVo = new UserAccountVo();
        userAccountVo.setMemberId(memberId);
        userAccountVo.setPileId(orderInfo.getElecPileId());
        userAccountVo.setOrderNum(orderInfo.getOrderNum());
        userAccountVo.setTenantCode(memberInfo.getTenantCode());

        //查地址表
        ElecPileHost elecPileHost = elecPileHostService.selectByPrimaryKey(userAccountVo.getPileId());

        //拼接eureka访问地址
        String requestUrl = RouterConfig.USER_ACCOUNT_PATH;
        if (HttpConstant.STD_DOMAIN.equals(elecPileHost.getElecServerDomain())) {
            requestUrl = "http://" + elecPileHost.getApplicationName() + RouterConfig.STD_SERVICE_PATH + RouterConfig.USER_ACCOUNT_PATH;
        } else {
            return TResponse.FAIL("暂无非标桩的余额下发功能");
//            requestUrl = "http://" + elecPileHost.getApplicationName() + RouterConfig.MUL_SERVICE_PATH + RouterConfig.MUTI_WECHAT_UNLOCK_PATH;
        }

        ObjectMapper objectMapper = new ObjectMapper();
        String respData = null;
        try {
            respData = objectMapper.writeValueAsString(userAccountVo);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        JSONObject tRequestJson = JSONObject.parseObject(respData);

        logger.info("std入参加密接口,余额下发接口被调用，...............对应url:{},手机号码:{}", requestUrl, memberInfo.getMobile());
        //通过rest调用远程服务接口
        ResponseEntity<TResponse> request = restTemplateUtil.request(requestUrl, HttpMethod.POST, tRequestJson, TResponse.class);
        logger.info("std入参加密接口,余额下发接口被调用，...............返回状态码:{},结果集:{}", request.getStatusCode(), request.getBody().toString());
        return request.getBody();
    }
}
